package com.zkingsoft.zkingbase.gen;

import android.content.Context;
import android.content.ContextWrapper;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * Created by ytf on 2017/2/28.
 * Description:
 */

public class GreenDaoContextWrapper extends ContextWrapper
{

    private Context mContext;
    private int dbRes;

    public GreenDaoContextWrapper(Context base, int localDbRes)
    {
        super(base);
        this.mContext = base;
        dbRes = localDbRes;
    }

    @Override
    public File getDatabasePath(String name)
    {
        String filePath = mContext.getDatabasePath(name).getAbsolutePath();
        File file = new File(filePath);
        if (!file.exists())
        {
            if(!file.getParentFile().exists())
            {
                file.getParentFile().mkdir();
            }
            copyDatabase(filePath);
        }
        return file;
    }

    /**
     * copy raw database：
     * /data/data/com.xxxx/databases/
     *
     * @param filePath
     */

    private void copyDatabase(String filePath)
    {
        InputStream inputStream = mContext.getResources().openRawResource(dbRes);
        FileOutputStream fos = null;
        try
        {
            fos = new FileOutputStream(filePath);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0)
            {
                fos.write(buffer, 0, length);
            }
            fos.flush();
            fos.close();
            inputStream.close();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory)
    {
        SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), factory);
        return result;
    }

    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler)
    {
        SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), factory);
        return result;
    }
}
